package com.janj.jdbc2;
//数据插入
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.sql.*;

public class Demo {
    Connection conn = null;
    Statement stat = null;
    ResultSet resu = null;

    @Before
    public void start() {
        try {
            String url = "jdbc:mysql://192.168.65.47:3306/duod9";
            String username = "root";
            String password = "root";
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int insertToDb(String name, Integer price) {
        int number = 0 ;

        try {
           //--------------
            //组装SQL语句  INSERT INTO phone VALUES (NULL,'iphone12 mini',21)

            String sql = "INSERT INTO phone VALUES(NULL,'" + name + "'," + price + ")";

            //1.获取到执行者的对象
            Statement stat = conn.createStatement();

            //2.执行SQL语句
           number = stat.executeUpdate(sql);

            //------------

        } catch (Exception e) {
            e.printStackTrace();
        }

        return number;
    }


    @Test
    public void testInsertToDb(){
        int num = insertToDb("Macbook pro",19998);
        System.out.println(num == 0 ? "操作失败" : "操作成功");
    }


    @After
    public void end() {
        if (resu != null) {
            try {
                resu.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}


